#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: resource.py
# Author: Tomás Vírseda
# License: GPL v3
# Description:  Identify resources
#               Extract, Fetch, Identify and Store the resource
#               Extract metadata: local, remote, event/note taken by user?
#               Fetch: store temporary a resource if remote. If it's a
#                      local resource, guess if vazaar should link
#                      against this resource or move it to the store.
#               Identify: all resources are identified
#                         by a unique URI Identifier.
#               Store: A vazaar store can be divided in two containers.
#                      1. Semantic container: all metadata and its
#                         relations are stored as rdf triples
#                         FIXME: use a database
#                      2. Data container: link, move or copy the resource into
#                         the data folder

# System imports
import os
from os.path import abspath
import datetime
import time
from stat import *
import sys
import types
from urlparse import urlparse, urlunparse
from hashlib import md5
import uuid
from rdflib.Graph import Graph
from rdflib import URIRef
from rdflib import BNode
from rdflib import Literal

from datetime import datetime

# Vazaar imports
#import pluginsystem as ps
from vazaarlib.metadata import Metadata
from vazaarlib.namespaces import *
from vazaarlib.utils import *


class Thing:
    store = Graph()
    cid = None

    def __init__(self):
        self.cid = self.get_thing_id()

    def serialize_rdfxml(self):
        try:
            print self.store.serialize(format="pretty-xml")
        except Exception:
            pass # log( "serialize_rdfxml:", e)

    def get_thing_id(self):
        identifier = URIRef("vazaar://" + str(uuid.uuid4()))
        return identifier

class Collection(Thing):
    def __init__(self, name):
        Thing.__init__(self)

        self.log = get_logger("Collection")
        self.cid = self.get_thing_id()
        now = datetime.now()

        self.store.add((self.cid, RDF.type, PIMO['Collection']))
        colname = "[DIR] " + os.path.basename(name)
        self.store.add((self.cid, NIE['title'], Literal(colname)))
        self.store.add((self.cid, NAO['created'], Literal(now)))


    def add(self, resource_id=None):
        try:
            self.store.add((self.cid, NIE['hasLogicalPart'], resource_id))
        except Exception, e:
            print "Collection:", e


class Resource(Thing):

    id = None

    def __init__ (self):
        Thing.__init__(self)

        self.log = get_logger("Resource")
        self.data = []
        self.store = Graph()
        self.id = self.get_thing_id()
        self.metadata = Metadata()

    def get_metadata(self, thing, thing_type):
        metadata = self.metadata.extract(self.id, thing, thing_type)

        if not metadata:
            return None

        try:
            for predicate, object in metadata:
                self.data.append((predicate, object))
        except Exception, error:
            self.log.debug(thing_type)

        """
        # get metadata from plugins
        # self.log.debug("activating plugins by 'get_metadata_from_%s'" % rtype)
        for plugin in ps.get_plugins_by_capability("get_metadata_from_%s" % rtype):
            metadata = plugin.do_something(arg)
            for p, o in metadata:
                self.data.append((p, o))
        """

        # Fetch
        # TODO
        self._fetch()

        # Identify
        #self._identify()

        # Build
        self._build()


    def _build(self):
        for tupla in self.data:
            s = self.id
            p = URIRef(tupla[0])
            o = tupla[1]
            triple = (s, p, o)
            self.store.add(triple)


    def _fetch(self):
        pass


    def _identify(self):
        self.id = self.get_thing_id()
        # self.log.debug("building new resource (%s)" % self.id)


